package com.dmcloud.zuul.ratelimit;

import com.dmcloud.common.util.reponse.ResultMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiaodao
 * date: 2019/11/7
 * 这里是限流错误的一些处理
 */
@Slf4j
public class GatewayRateLimitFilter extends OncePerRequestFilter {

    private RateLimiter rateLimiter =  RateLimiter.create(500);
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.err.println("0 rate limit ");
        if(rateLimiter.tryAcquire()){
            filterChain.doFilter(httpServletRequest,response);
        }else {
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.setContentType("application/json");
            String json = objectMapper.writeValueAsString(ResultMessage.errorMsg(200, "访问过于频繁请稍后再试!"));
            response.getWriter().write(json);
            response.getWriter().flush();
        }
    }
}
